<?php
/**
 * Controller pre admin-acl
 * @author Tomas Srna
 * @package bakalarka
 */

class AdminAclController extends Controller 
{
	protected $resource = 'admin-acl';
	
	/**
	 * Index
	 */
	public function index()
	{
		$t = Template::instance();
		
		$dv = new DynamicView();
		$dv->buttonAdd = true;
		$dv->primaryKeys = array('role', 'resource');
		$dv->baseUrl = APPBASE."admin/acl";
		
		$dv->itemCount = Selector::select("count(*) as c")->from('acl')
			->fetch()->current()->c;
			
		$t->dv = $dv;
		$t->dvw = new DynamicViewWriter($t->dv, $t);
		
		$t->title = L::selected()->aclAdmin;
		$t->text = "";
		
		$t->render('dynamic-view');
	}

	/**
	 * Data
	 */
	public function data()
	{
		$params = $_GET;
		
		$t = Template::instance();
		
		// Kontrola vstupov
		$by_possible = array("role", "resource", "allow");
		
		$dt = new DynamicTable();
		$dt->primaryKeys = array('role', 'resource');
		$dt->itemCount = Selector::select("count(*) as c")->from('acl')
			->fetch()->current()->c;
		
		if(!$dt->check($params, $by_possible))
			$t->error = L::selected()->invalidInput;
			
		if(!property_exists($t, 'error'))
		{
			$dt->headers['role'] = L::selected()->role;
			$dt->headers['resource'] = L::selected()->resource;
			$dt->headers['allow'] = L::selected()->action;
			
			$dt->writers['allow'] = new AclActionWriter();
			
			if(!array_key_exists('page', $params))
				$params['page'] = 1;
			
			$select = Selector::select()
						->from(AclModel::struct())
						->page($params['page'])
						->by($params);
			
			$dt->data = $select->fetch();
			
			$t->dtw = new DynamicTableWriter($dt, $t);
		}
			
		$t->dt = $dt;
		$t->render('dynamic-table');
	}

	/**
	 * Edit
	 * @param bool $create		Vytvarame noveho uzivatela?
	 */
	public function edit($create = false)
	{
		$t = Template::instance();
		
		if($create)
		{
			$t->title = L::selected()->createAcl;
			if(getenv('REQUEST_METHOD') == 'POST')
				$model = AclModel::create($_POST);
			else
				$model = NULL;
		}
		else
		{
			$t->title = L::selected()->editAcl;
			
			// Skontrolujeme ci existuje objekt a nacitame ho
			if(	!array_key_exists('role', $_GET) ||
				!array_key_exists('resource', $_GET))
				throw new Exception('L::errorObjectNotFound;'.
						json_encode(array('AclModel(?, ?)')));
						
			$model = AclModel::load(array(
						'role' => $_GET['role'],
						'resource' => $_GET['resource']
					));
			if(!$model)
				throw new Exception('L::errorObjectNotFound;'.
					json_encode(array(sprintf('AclModel(%s, %s)',
					$_GET['role'], $_GET['resource']))));
		}
		
		if(getenv('REQUEST_METHOD') == 'POST')
		{
			$f = new AclForm($t, $_POST);
			
			if($f->validate())
			{
				// Kontrola duplicity
				if($create)
					$dup = AclModel::load(array(
						'role' => $_POST['role'],
						'resource' => $_POST['resource'],
					));
				
				if(!$create || $dup == NULL)
				{
					$model->set($_POST);
					$model->save();
					if($create)
						Logger::log('L::objectCreated_s;'.
							json_encode((string)$model), 'info');
					else
						Logger::log('L::objectChanged_s;'.
							json_encode((string)$model), 'info');
					$this->autoredir();
				}
				else
					$t->error = L::selected()->duplicity;
			}
			else
				$t->error = L::selected()->invalidForm;
		}
		else
		{
			$f = new AclForm($t, $model);
		}
		
		$fw = new FormWriter($f);
		$t->fw = $fw;
		
		$t->render('form');
	}

	/**
	 * Vytvorenie noveho ACL zaznamu
	 */
	public function create()
	{
		// Zavolame edit s $create = true
		return $this->edit(true);
	}
	
	/**
	 * Odstranenie riadka
	 */
	public function delete()
	{
		// Skontrolujeme ci existuje objekt a nacitame ho
		if(	!array_key_exists('role', $_GET) || 
			!array_key_exists('resource', $_GET))
			throw new Exception('L::errorObjectNotFound;'.
					json_encode(array('AclModel(?, ?)')));
					
		$model = AclModel::load(array(
			'role' => $_GET['role'],
			'resource' => $_GET['resource'],
		));
		if(!$model)
			throw new Exception('L::errorObjectNotFound;'.
				json_encode(array(sprintf('UserModel(%s)', $_GET['username']))));
				
		// Zmazeme vsetky zavislosti
		// -- ziadne
		
		// Zmazeme samotny riadok
		$model->delete();
		
		// Zalogujeme
		Logger::log('L::objectDeleted_s;'.
			json_encode((string)$model), 'info');
		
		$this->autoredir();
	}
}
